package com.atguigu.gmall.auth.service;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.AuthException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Service
public class AuthService {
    @Autowired
    private GmallUmsClient gmallUmsClient;
    @Autowired
    private JwtProperties jwtProperties;
    public void login(HttpServletRequest request, HttpServletResponse response, String loginName, String password) {

        try {
            //校验用户
            ResponseVo<UserEntity> responseVo = gmallUmsClient.queryuser(loginName, password);
            UserEntity userEntity = responseVo.getData();

            //判断用户是否为null
            if (userEntity == null){
                throw new AuthException("用户不存在");
            }

            //组装载荷map：用户id、用户名
            HashMap<String, Object> map = new HashMap<>();
            map.put("userId",userEntity.getId());
            map.put("username",userEntity.getUsername());

            //为了防止盗用，必须放入登录用户ip
            String ip = IpUtils.getIpAddressAtService(request);
            map.put("ip",ip);

            //生成jwt类型的token
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());

            //放入cookie
            CookieUtils.setCookie(request,response,
                    jwtProperties.getCookieName(),token,jwtProperties.getExpire() * 60);

            //为了展示登录状态，cookie加入昵称
            CookieUtils.setCookie(request,response,
                    jwtProperties.getUnick(),userEntity.getNickname(),jwtProperties.getExpire() * 60);
            CookieUtils.setCookie(request,response,"userId",userEntity.getId().toString(),jwtProperties.getExpire() * 60);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
